How to Add JavaScript to an HTML Document

JavaScript is a programming language that helps make web pages interactive. Here are three ways to add JavaScript to an HTML file:

1. Adding JavaScript Inside the <head> Tag

You can write JavaScript inside the <head> tag. This means the JavaScript runs when the webpage starts loading.

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        function sayHello() {
            alert("Hello from Javascript in Head!");
        }
    </script>
</head>
<body>
    <button onclick="sayHello()" >click me</button>
</body>
</html>
                            
2. Adding JavaScript Inside the <body> Tag

Another way to add JavaScript is inside the <body> tag, usually at the end of the page content. This ensures the page content loads first, and then the script runs.

<!DOCTYPE html>
<html lang="en">
<body>
    <button onclick="sayHelloFromBody()" >click me</button>
    <script>
          function sayHelloFromBody() {
               alert("Hello from AIT in Body!");
          }
    </script>
</body>
</html>
                            
3. Adding External JavaScript

You can also write JavaScript in a separate file and link it to your HTML. This helps keep your HTML clean and organized.

// Index.Html File Content
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <button onclick="sayHelloExternal()" >click me</button>
    <script src="script.js" ></script>
</body>
</html>

// script.js file content
function sayHelloExternal() {
    alert("Hello from External JavaScript!");
}

                            
Output

In each example, clicking the button will display a pop-up message using JavaScript.